package org.example.io;

import java.io.*;

/**
 * @description:
 * @author: farprt
 * @create: 2022-08-16 00:22
 **/
public class BinaryFileUtils {

    //将文件全部内容读入到一个字符串，参数为文件名和编码类型
    public static String readFileToString(final String fileName,final String encoding) throws IOException{
        BufferedReader reader=null;
        try {
            reader=new BufferedReader(new InputStreamReader(new FileInputStream(fileName),encoding));
            StringWriter writer=new StringWriter();
            copy(reader,writer);
            return writer.toString();
        }finally {
            if(reader!=null){
                reader.close();
            }
        }
    }

    //复制Reader到Writer
    public static void copy(final Reader input,final Writer output) throws IOException {
        char[] buf=new char[4096];
        int charsRead=0;
        while ((charsRead=input.read(buf))!=-1){
            output.write(buf,0,charsRead);
        }
    }

    public static void copy(InputStream input,OutputStream output) throws IOException {
        byte[] buf=new byte[4096];
        int bytesRead=0;
        while ((bytesRead=input.read(buf))!=-1){
            output.write(buf,0,bytesRead);
        }
    }

    public static byte[] readFileToByteArray(String fileName) throws IOException {
        InputStream input=new FileInputStream(fileName);
        ByteArrayOutputStream output=new ByteArrayOutputStream();
        try {
            copy(input,output);
            return output.toByteArray();
        }finally {
            input.close();
        }


    }
}